//
//  UserLoginModalViewController.m
//  LoveHealth
//
//  Created by lanou3g on 14-9-23.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "UserLoginModalViewController.h"

@interface UserLoginModalViewController ()<UIWebViewDelegate>

@property(nonatomic,retain)UIWebView * loginWebView;
@property (nonatomic,retain)NSMutableDictionary * userInfoDic;
@end

@implementation UserLoginModalViewController

- (void)dealloc
{
    self.userInfoVC = nil;
    self.userInfoDic = nil;
    self.loginWebView = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"加载中";
    NSLog(@"%ld",self.loginType);
    
    //导航栏返回按钮
    UIBarButtonItem * leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(didClickReturnBackAction:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.userInfoDic = [NSMutableDictionary dictionary];
    
    _loginWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height)];
    
    [self.view addSubview:_loginWebView];
    self.loginWebView.delegate = self;
    NSString * loginUrl = nil;
    if (self.loginType == QQType) {
        loginUrl = APIQQLogin;
    }else if(self.loginType == SinaType){
        loginUrl = APISinaLogin;
    }
    [self.loginWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:loginUrl]]];
}

//点击返回按钮触发事件
- (void)didClickReturnBackAction:(UIBarButtonItem *)barButtonItem
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.navigationItem.title = @"登录";
    //NSString *jsToGetHTMLSource = @"document.documentElement.innerHTML";
    NSString * jsToGetHTMLBody = @"document.body.innerText";
    NSString * bodyText = [webView stringByEvaluatingJavaScriptFromString:jsToGetHTMLBody];
    //NSLog(@"%@",bodyText);
    if ([bodyText hasPrefix:@"{"]) {
        NSArray * array = [bodyText componentsSeparatedByString:@"\""];
        NSLog(@"%@",array);
        NSLog(@"cede ======%@",array[1]);
        [self.userInfoDic setObject:array[1] forKey:kLoginCode];
        
        //__block UserLoginModalViewController * userloginVC = self;
        [self dismissViewControllerAnimated:YES completion:^{
            
            NSString * urlString = [NSString stringWithFormat:@"%@%@",APIAccessToken,self.userInfoDic[kLoginCode]];
            
            
            [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"%@",sourceDic);
                [self.userInfoDic setObject:sourceDic[kLoginAccess_token] forKey:kLoginAccess_token];
                [self.userInfoDic setObject:sourceDic[kLoginRefresh_token] forKey:kLoginRefresh_token];
                
                NSString * userInfoUrl = [NSString stringWithFormat:@"%@%@",APIUserInfo,self.userInfoDic[kLoginAccess_token]];
                
                [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:userInfoUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    
                    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSDictionary * newDic = dic[@"yi18"];
                    [self.userInfoDic setObject:newDic[kLoginAccount] forKey:kLoginAccount];
                    [self.userInfoDic setObject:newDic[kLoginImageUrl] forKey:kLoginImageUrl];
                    
                    NSString * imageUrl = APIImageURL(self.userInfoDic[kLoginImageUrl]);
                    NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
                    [self.userInfoDic setObject:imageData forKey:kloginImage];
                    [self.userInfoVC.tableView reloadData];
                    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:self.userInfoDic forKey:KLoginUserInfo];
                    //同步数据
                    [userDefaults synchronize];
                    
                }];

                
            }];
            
            
            
        }];
        
        /*NSString * url = [NSString stringWithFormat:@"http://api.yi18.net/oauth2/accesstoken?client_id=wwwyi18net&client_secret=yi18net&grant_type=authorization_code&redirect_uri=http://m.yi18.net/oauth2/token&&code=authorization_code&refresh_token=%@",array[1]];
        [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",sourceDic);
            
            NSString * access_token = sourceDic[@"access_token"];
            
            NSString * userUrl = [NSString stringWithFormat:@"http://api.yi18.net/user/info?access_token=%@",access_token];
            
            [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:userUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSDictionary * newDic = dic[@"yi18"];
                NSLog(@"%@",newDic[@"account"]);
                NSString * imageUrl = [NSString stringWithFormat:@"http://www.yi18.net/%@",newDic   [@"avatar"]];
                NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
                self.imageView.image = [UIImage imageWithData:imageData];
            }];
        }];*/
    }

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
